package com.service.config.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * DES加密 解密算法
 * @author zhangdi
 *
 */
public class DesUtil {
    private static final Logger LOG = LoggerFactory.getLogger(DesUtil.class);
    private final static String DES = "DES";
    private final static String ENCODE = ParamUtils.DEFAULT_ENCODE;
    private final static String DEFAULT_KEY = "systemCode";
    private final static String[] A = {"\\+","\\\\"};
    private final static String[] B = {"@WA01AW@","@WA02AW@"};
    static final Base64.Encoder basEncoder = Base64.getEncoder();
    static final Base64.Decoder decoder = Base64.getDecoder();

    public static String a2b(String data) throws Exception {
        for(int i=0;i<A.length;i++){
            data=data.replaceAll(A[i],B[i]);
        }
        return  data;
    }
    public static String b2a(String data) throws Exception {
        for(int i=0;i<B.length;i++){
            data=data.replaceAll(B[i],A[i]);
        }
        return  data;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("1");
        String encrypt1 = decrypt("TcW0pVAlBs9cWvs87c1A3A==");

        String encrypt2 = encrypt("1");
        System.out.println("string  "+encrypt);
        System.out.println("string2  "+encrypt1);
        System.out.println("string4 "+encrypt2);


    }
    /**
     * BASE64编码
     * @param data
     * @return
     * @throws Exception
     */
    public static String encodeToString(String data) throws Exception {
        if (data != null) {
            byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
            data = basEncoder.encodeToString(bytes);
        }
        return data;
    }
    /**
     * BASE64解码
     * @param data
     * @return
     * @throws Exception
     */
    public static String decodeToString(String data) throws Exception {
        if (data != null) {
            byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
            data =new String(decoder.decode(bytes),StandardCharsets.UTF_8) ;
        }
        return data;
    }
    /**
     * BASE64+Url编码
     * @param data
     * @return
     * @throws Exception
     */
    public static String encodeUrlToString(String data) throws Exception {
        if (data != null) {
            data = URLEncoder.encode(data, "UTF-8").replace("+", "%20");
            data = URLEncoder.encode(data,"UTF-8");
        }
        return data;
    }
    public static String decodeUrlToString(String data) throws Exception {
        if (data != null) {
            data = URLDecoder.decode(data);
        }
        return data;
    }
    /**
     * 使用 默认key 加密
     * @param data 待加密数据
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) throws Exception {

        byte[] bt = encrypt(data.getBytes(ENCODE), DEFAULT_KEY.getBytes(ENCODE));
        String strs = new BASE64Encoder().encode(bt);
        strs=a2b(strs);
        return strs;
    }

    /**
     * 使用 默认key 解密
     * @param data 待解密数据
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data) throws IOException, Exception {
        if (data == null) {
            return null;
        }
        data=b2a(data);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, DEFAULT_KEY.getBytes(ENCODE));
        String temp=new String(bt, ENCODE);

        return temp;
    }

    /**
     * Description 根据键值进行加密
     * @param data 待加密数据
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), key.getBytes(ENCODE));
        String s = new BASE64Encoder().encode(bt);
        s = a2b(s);
        return s;
    }

    /**
     * 根据键值进行解密
     * @param data 待解密数据
     * @param key    密钥
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
            Exception {
        return getString(data, key);
    }

    private static String getString(String data, String key) throws Exception {
        if (data == null) {
            return null;
        }
        data=b2a(data);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, key.getBytes(ENCODE));
        String temp=new String(bt, ENCODE);
        return temp;
    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secureKey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);

        return cipher.doFinal(data);
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key 加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }


}
